/**
 * @description: 文件描述
 * @version: 0.0.1
 * @author: ljr
 * @Date: 2023-09-12 15:47:16
 */
import { Provide, Inject } from '@midwayjs/core';
import { ProjectRecordModel } from '../entity/project_records.methods';
import { ProjectOrderContactModel } from '../entity/project_order_contact.methods';
import { WorkingRecordsModel } from '../entity/working_records.methods';
import { OrdersRecordsModel } from '../entity/orders_records.methods';
import { Context } from '@midwayjs/koa';

@Provide()
export class ProjectService {
  @Inject()
  ctx: Context;

  @Inject()
  ProjectRecordModel: ProjectRecordModel;

  @Inject()
  ProjectOrderContactModel: ProjectOrderContactModel;

  @Inject()
  WorkingRecordsModel: WorkingRecordsModel;

  @Inject()
  OrdersRecordsModel: OrdersRecordsModel;
  /**
   * 获取项目列表
   * @param {*} 无
   * @return
   */
  async getProjLists(): Promise<any> {
    return await this.ProjectRecordModel.getProjLists()
  }

  /**
   * 项目列表分页查询
   * @param {*} params 
   */
  async getProjPage(params: any): Promise<any> {

    const { pageSize, pageNum, searchKey, orderId } = params;
    // const { num } = await this.ProjectRecordModel.getTotalNum(searchKey);
    // const res = {
    //   total: num,
    //   lists: []
    // }
    // if (num) {
    //   const resList = await this.ProjectRecordModel.getDataByPage(pageNum, pageSize, searchKey);
    //   res.lists = resList;
    // }
    // return res
    return await this.ProjectRecordModel.getDataByPageByOrderId(pageNum, pageSize, searchKey, orderId)

  }

  /**
   * 删除项目数据
   * @param {*} id
   */
  async delProjInfo(params: any): Promise<any> {
    //删除项目信息
    await this.ProjectRecordModel.delDataById(params.id)
    //  删除当前项目关联的订单数据
    await this.ProjectOrderContactModel.delContact(params.id);
    return '删除成功'
  }

  /**
  * 新增项目信息
  * @param {*} params 
  * @returns 
  */
  async createdProj(params: any): Promise<any> {
    const {ctx} = this;
    const userInfo = ctx.userInfo;

    const { projectName, projectContent, projectProgress, projectType, userId, userName, orderId, brandName } = params;

    const orderArr = orderId ? orderId.split(",") : [];

    const insertRes = await this.ProjectRecordModel.insertProjectInfo({
      projectName: projectName,
      projectContent: projectContent || "",
      projectProgress: projectProgress || "",
      projectType: projectType || "",
      userId: userId || "",
      userName: userName || "",
      createUserid: userInfo.id,
      createUsername: userInfo.nick,
      brandName: brandName || ""
    });

    if (!insertRes) return Promise.reject("项目新增失败")

    //  新增项目和订单的关联关系
    for (let i = 0; i < orderArr.length; i++) {
      // 查询项目订单关联关系是否存在
      const count = await this.ProjectOrderContactModel.countContact({
        projId: insertRes,
        orderId: orderArr[i]
      });
      // 新增关联关系
      if (!count[0].total) {
        await this.ProjectOrderContactModel.insertContact({
          projId: insertRes,
          orderId: orderArr[i]
        })
      }
    }
    return insertRes
  }
  /**
   * 修改项目信息
   * @param {*} params 
   */
  async updatedProj(params: any): Promise<any> {

    await this.ProjectRecordModel.updateProjectInfo({
      id: params.id,
      projectName: params.projectName,
      projectContent: params.projectContent || "",
      projectProgress: params.projectProgress || "",
      projectType: params.projectType || "",
      userId: params.userId || "",
      userName: params.userName || "",
      brandName: params.brandName || "",
    });

    //  更新工时绑定的项目名称
    await this.WorkingRecordsModel.updateProjectsNameById(params.id, params.projectName)

    return "修改成功";
  }

  /**
    * 获取项目详情
    * @param {*} params 
    */
  async getProjById(params: any): Promise<any> {
    const projRes = await this.ProjectRecordModel.getProjById(params.id);
    if (!projRes || !projRes.length) return Promise.reject("未查询到项目信息")
    // 查询当前项目所填工时信息
    const workingList = await this.WorkingRecordsModel.getWorkingByProjId(params.id);
    // 查询当前项目关联的订单信息
    const orderList = await this.ProjectOrderContactModel.getOrderDataByProjId(params.id);
    return {
      project: projRes[0],
      workingList,
      orderList
    }
  }

  /**
   * 项目绑定订单数据
   * @param {*} projId    项目id 
   * @param {*} orderId   订单id 
   * @param {*} isBind   绑定还是解绑 
   */
  async updateProjOrderContact(params: any): Promise<any> {
    const { projId, orderId, isBind } = params;

    const projRes = await this.ProjectRecordModel.getProjById(projId);
    if (!projRes || !projRes.length) return Promise.reject("未查询到项目信息")

    if (isBind) {
      //  查询当前绑定关系是否存在
      // const count = await this.ProjectOrderContactModel.countContact({ projId, orderId });
      // if (count[0].total) return Promise.reject("当前绑定关系已存在，无法继续绑定");
      const count = await this.ProjectOrderContactModel.countContactByProj({ projId });
      if (count[0].total) return Promise.reject("当前项目已关联订单，无法继续绑定");
      //  验证订单数据是否存在
      const count2 = await this.OrdersRecordsModel.getCountById(orderId);
      if (!count2[0].total) return Promise.reject("当前绑定订单数据不存在");

      // 绑定
      await await this.ProjectOrderContactModel.insertContact({ projId, orderId });
      return "绑定成功"
    } else {
      // 解绑
      await await this.ProjectOrderContactModel.delOrderContact({ projId, orderId });
      return "解绑成功"
    }

  }
}









